package net.guerlab.smart.wx.internal.controller.inside;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.bean.WxCpOauth2UserInfo;
import net.guerlab.commons.exception.ApplicationException;
import net.guerlab.smart.wx.core.domain.WxCpOauth2UserInfoDTO;
import net.guerlab.smart.wx.service.service.WxCpManagerService;
import net.guerlab.web.result.Result;
import net.guerlab.web.result.Succeed;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 企业微信
 *
 * @author guer
 */
@Api(tags = "企业微信")
@RestController("/inside/wx/cp")
@RequestMapping("/inside/wx/cp")
@Transactional(rollbackFor = Exception.class)
public class WxCpController {

    private WxCpManagerService managerService;

    @ApiOperation("获取")
    @GetMapping("/{appId}/accessToken")
    public Result<String> getAccessToken(@ApiParam(value = "应用ID", required = true) @PathVariable String appId) {
        try {
            return new Succeed<>(Succeed.MSG, managerService.getService(appId).getAccessToken());
        } catch (WxErrorException e) {
            throw new ApplicationException(e.getError().getErrorMsg(), e.getError().getErrorCode());
        }
    }

    @ApiOperation("通过code获取用户信息")
    @GetMapping("/{appId}/{code}/getCodeInfo")
    public WxCpOauth2UserInfoDTO getCodeInfo(@ApiParam(value = "应用ID", required = true) @PathVariable String appId,
            @ApiParam(value = "code", required = true) @PathVariable String code) {
        try {
            WxCpOauth2UserInfo userInfo = managerService.getService(appId).getOauth2Service().getUserInfo(code);

            WxCpOauth2UserInfoDTO dto = new WxCpOauth2UserInfoDTO();
            dto.setOpenId(userInfo.getOpenId());
            dto.setDeviceId(userInfo.getDeviceId());
            dto.setUserId(userInfo.getUserId());
            dto.setUserTicket(userInfo.getUserTicket());
            dto.setExpiresIn(userInfo.getExpiresIn());

            return dto;
        } catch (WxErrorException e) {
            throw new ApplicationException(e.getError().getErrorMsg(), e.getError().getErrorCode());
        }
    }

    @Autowired
    public void setManagerService(WxCpManagerService managerService) {
        this.managerService = managerService;
    }
}
